<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-input-container">
				<text class="iconfont">&#xe61b;</text>
				<input type="text" v-model="searchWord" placeholder="搜索商品" @confirm="searchGoods" />
			</view>
			<view class="cancel-btn" @click="searchGoods">搜索</view>
		</view>

		<!-- 搜索结果 -->
		<view class="search-result" v-if="searchWord">
			<view class="result-header">
				<text>搜索结果: {{searchWord}}</text>
			</view>

			<view class="goods-list" v-if="goodsList.length > 0">
				<view class="goods-item" v-for="goods in goodsList" :key="goods.id">
					<view class="goods-image" @click="navigateToDetail(goods.id)">
						<image :src="goods.thumb" mode="aspectFill"></image>
					</view>
					<view class="goods-info" @click="navigateToDetail(goods.id)">
						<text class="goods-name">{{goods.goods_name}}</text>
						<text class="goods-description">{{goods.description}}</text>
						<text class="goods-price">{{goods.sell_price}}元/{{goods.company}}</text>
						<text class="goods-stock">库存: {{goods.num}}</text>
					</view>
					<button class="add-cart-btn" type="primary" size="mini" @click="showSpecModal(goods)">加入购物车</button>
				</view>
			</view>

			<view class="no-result" v-else>
				<text>暂无搜索结果</text>
			</view>
		</view>

		<!-- 热门搜索 -->
		<view class="hot-search" v-else>
			<view class="hot-header" v-if="hotTags.length > 0">
				<text>热门搜索</text>
			</view>
			<view class="hot-tags">
				<view class="tag" v-for="tag in hotTags" :key="tag">
					<text @click="searchByTag(tag)">{{tag}}</text>
					<text class="delete-btn" @click.stop="deleteTag(tag)">×</text>
				</view>
			</view>
		</view>

		<!-- 规格选择弹窗组件 -->
		<spec-modal v-if="currentGoods" :goods="currentGoods" :show.sync="specModalShow"
			@confirm="handleSpecConfirm"></spec-modal>
	</view>
</template>

<script>
	import specModal from '../../components/specModal.vue';
	import api from '../../api/request';

	export default {
		components: {
			specModal
		},
		data() {
			return {
				searchWord: '', // 搜索关键词
				goodsList: [], // 搜索结果商品列表
				hotTags: [], // 热门搜索标签
				currentGoods: null, // 当前选中的商品
				specModalShow: false, // 规格弹窗显示状态
				currentPage: 1,
			};
		},
		onLoad(options) {
			// 从缓存加载历史搜索记录
			const history = uni.getStorageSync('searchHistory');
			if (history && Array.isArray(history)) {
				this.hotTags = history;
			}

			// 如果从其他页面携带搜索关键词过来
			if (options && options.keyword) {
				this.searchWord = options.keyword;
				this.searchGoods();
			}
		},
		onReachBottom() {
			if (this.hasMore) {
				this.currentPage++;
				this.searchGoods();
			}
		},
		methods: {
			// 搜索商品
			searchGoods() {
				if (!this.searchWord.trim()) {
					return;
				}

				const params = {
					page: this.currentPage,
					search_word: this.searchWord
				};

				api.getGoodsList(params)
					.then(res => {

						if (res.code == 1 && res.data && res.data.rows) {
							this.total = res.data.total;

							if (this.currentPage == 1) {
								this.goodsList = res.data.rows;
							} else {
								this.goodsList = [...this.goodsList, ...res.data.rows];
							}

							// 判断是否还有更多数据
							this.hasMore = this.goodsList.length < this.total;
						} else {
							this.goodsList = [];
						}
					})
					.catch(err => {
						console.error('搜索商品失败:', err);
						this.goodsList = [];
					});
			},

			// 热门标签搜索
			searchByTag(tag) {
				this.searchWord = tag;
				this.searchGoods();

				// 将搜索标签添加到hotTags（如果不存在）
				if (!this.hotTags.includes(tag)) {
					this.hotTags.unshift(tag);
					// 限制hotTags数量
					if (this.hotTags.length > 10) {
						this.hotTags.pop();
					}
					// 保存到缓存
					uni.setStorageSync('searchHistory', this.hotTags);
				}
			},

			// 删除搜索标签
			deleteTag(tag) {
				// 从hotTags中删除
				this.hotTags = this.hotTags.filter(item => item !== tag);
				// 更新缓存
				uni.setStorageSync('searchHistory', this.hotTags);
			},

			// 显示规格选择弹窗
			showSpecModal(goods) {
				this.currentGoods = goods;
				this.specModalShow = true;
			},

			// 跳转到商品详情页
			navigateToDetail(goodsId) {
				uni.navigateTo({
					url: `/pages/goods/detail?goods_id=${goodsId}`
				})
			},

			// 处理规格确认
			handleSpecConfirm(data) {
				const params = {
					goods_id: data.goods.id,
					num: data.num,
					item: data.spec.id
				};

				api.addCart(params)
					.then(res => {
						uni.showToast({
							title: '添加购物车成功',
							icon: 'success'
						});
					})
					.catch(err => {
						uni.showToast({
							title: '添加购物车失败',
							icon: 'none'
						});
					});
			}
		}
	};
</script>

<style scoped>
	/* 搜索框样式 */
	.search-container {
		display: flex;
		align-items: center;
		padding: 10px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.search-input-container {
		flex: 1;
		display: flex;
		align-items: center;
		height: 40px;
		background-color: #f5f5f5;
		border-radius: 20px;
		padding: 0 15px;
	}

	.search-input-container .iconfont {
		color: #999;
		margin-right: 5px;
	}

	.search-input-container input {
		flex: 1;
		font-size: 14px;
	}

	.cancel-btn {
		width: 60px;
		text-align: center;
		font-size: 14px;
		color: #333;
	}

	/* 搜索结果样式 */
	.search-result {
		padding: 10px;
	}

	.result-header {
		padding: 10px 0;
		font-size: 14px;
		color: #666;
		border-bottom: 1px solid #eee;
	}

	/* 热门搜索样式 */
	.hot-search {
		padding: 10px;
	}

	.hot-header {
		padding: 10px 0;
		font-size: 14px;
		color: #666;
		border-bottom: 1px solid #eee;
	}

	.hot-tags {
		display: flex;
		flex-wrap: wrap;
		padding: 10px 0;
	}

	.tag {
		margin: 5px;
		padding: 5px 10px;
		background-color: #f5f5f5;
		border-radius: 15px;
		font-size: 14px;
		color: #333;
		position: relative;
		padding-right: 25px;
	}

	.delete-btn {
		position: absolute;
		right: 8px;
		top: 50%;
		transform: translateY(-50%);
		color: #999;
		font-size: 12px;
		cursor: pointer;
	}

	.delete-btn:active {
		color: #e63946;
	}

	/* 商品列表样式 */
	.goods-list {
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding: 10px 0;
	}

	.goods-item {
		display: flex;
		/* width: 100%; */
		margin-bottom: 10px;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		position: relative;
		padding: 10px;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
	}

	.goods-image {
		width: 120px;
		height: 120px;
		margin-right: 10px;
		flex-shrink: 0;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		margin-bottom: 5px;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-description {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 12rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-price {
		font-size: 16px;
		color: #e63946;
		font-weight: bold;
	}

	.goods-stock {
		font-size: 12px;
		color: #999;
	}

	.add-cart-btn {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		background-color: #FE0000;
		color: #fff;
		font-size: 24rpx;
		padding: 0 20rpx;
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 25rpx;
		z-index: 10;
	}

	/* 无结果样式 */
	.no-result {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200px;
		color: #999;
	}
</style>